<template>
  <page-meta :root-font-size="rootFontSize() + 'px'"> </page-meta>

  <view class="page-container" v-show="delayShow">
    <customHeader :isShowProcess="!isOraVideo || isSynthesis" :isShowBottomImage="isOraVideo && !isSynthesis"
      :progress="progress" title="口语模仿" />

    <view class="oral-container" :style="{ top: height }">
      <view v-if="!isOraVideo || isSynthesis" class="oral-wrapper">
        <text class="oral-title">听音频，进行复述练习</text>
        <image class="oral-image" :src="`${env.prefixUrl}${currentDetail?.img}`" />
        <loudspeaker class="oral-speaking" isAutoPlay :voice="currentDetail?.us_voice" />

        <view class="oral-score-popup" v-if="isShowPopup">
          <view class="oral-score-label">
            <text class="label">综合得分：</text>
            <text :class="['score', currentScore >= scoreLimit ? 'success' : 'error']">{{ currentScore }}</text>
          </view>
          <view class="oral-score-desc" @click="handleRepairPhoneme">
            <view class="desc" v-if="currentScore >= scoreLimit || speakTimes <= 0">
              查看完成分析
              <image class="right" src="https://rwstatic.tentons.cn/web/Lesson/images/score-popup-right.png" />
            </view>
            <text class="desc" v-else>请尝试重新录音答题</text>
          </view>
        </view>

        <record-sound :title="operateTitle" :isShowSubBtn="isShowSubBtn" @on-upload-success="onRecorderSuccess"
          @sub-click="handleSetOperate" @main-click="handleSetPopup" />
      </view>

      <view v-if="isOraVideo && !isSynthesis" class="video-container">
        <oralVideo :isRelearn="isRelearn" :isReStart="isReStart" :section_id="sectionId" @re-start="handleReStart" />
      </view>
    </view>
  </view>
  <CwCommon />
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { rootFontSize, util } from "@/utils/util";
import customHeader from "@/components/customHeader.vue";
import loudspeaker from "@/components/loudspeaker.vue";
import oralVideo from "./oralVideo.vue";
import recordSound, { type IUploadSuccessInfo } from "@/components/recordSound.vue";
import { startEvaluating } from "@/utils/chivox";
import { onLoad } from "@dcloudio/uni-app";
import env from "@/config/env";
import API from "@/api";
// @ts-ignore
import { ossDownLoad } from "@/utils/oss/oss.js";
import type { IOralImitation, IOralImitationLesson } from "./index";
import { useDelayShow } from "@/hooks/useDelayShow";

const { delayShow } = useDelayShow();
const fs = uni.getFileSystemManager();
const height = ref(getApp().globalData!.pageProcessTop);

const sectionId = ref("");
const progress = ref(0);
const currentIndex = ref(0);
const scoreLimit = ref(0);
const currentScore = ref(0);
const imitationList = ref<IOralImitation[]>([]);
const stepWidth = ref(0);
const isShowSubBtn = ref(false);
const operateTitle = ref("复述句子");
const isShowPopup = ref(false);
const currentMap = ref(new Map());
const courseStep = ref(0);
const isSynthesis = ref(true); // 是否是口语综合
const speakTimes = ref(2); // 单次录音2次跳过
const isRelearn = ref(false); // 是否重学
const isReStart = ref(false);
const isOraVideo = ref(false); // 是否展示总结视频

const currentDetail = computed(() => {
  return imitationList.value[currentIndex.value];
})

onLoad(async (option: any) => {
  sectionId.value = option.section_id;
  courseStep.value = Number(option.courseStep);
  if (option.isSynthesis) {
    isSynthesis.value = option.isSynthesis === "true";
  }

  if (option.data) {
    const result: IOralImitationLesson = JSON.parse(decodeURIComponent(option.data));

    isRelearn.value = result.isRelearn;
    isOraVideo.value = result.isRelearn;
    scoreLimit.value = result.data.scoreLimit;
    imitationList.value = result.data.questions;
    stepWidth.value = result.data.stepLength;
    currentIndex.value = result.data.currentQuestionIndex;
    progress.value = Math.min(100, stepWidth.value * currentIndex.value);
  }
});

const onRecorderSuccess = (info: IUploadSuccessInfo) => {
  util.showLoading();

  fs.readFile({
    filePath: info.localFilePath,
    success: (file) => {
      startEvaluating({
        evaluatingInfo: { sentence: currentDetail.value.sentences },
        audioBuffer: file.data as ArrayBuffer,
        onSuccess: async (res) => {
          const evaResult = await API.oralImitationReport({
            section_id: sectionId.value,
            oral_imitation: [{
              oral_id: currentDetail.value.oral_id,
              user_voice: info.ossFilePath,
              analysis: JSON.stringify(res),
            }]
          }) as {
            scoreLimit: number,
            result: any[],
          }

          isShowPopup.value = true;
          operateTitle.value = "重新录音";
          currentScore.value = evaResult.result[0].score;

          if (currentScore.value >= scoreLimit.value) {
            speakTimes.value = 2;
            isShowSubBtn.value = true;
          } else {
            speakTimes.value -= 1;
            isShowSubBtn.value = false;
          }

          if (speakTimes.value <= 0) {
            isShowSubBtn.value = true;
          }

          currentMap.value.set(currentDetail.value.oral_id, Object.assign(evaResult.result[0], {
            type: courseStep.value,
            user_voice: info.ossFilePath,
            sentences: currentDetail.value.sentences,
          }));

          util.hideLoading();
        },
        onError: (errMsg) => {
          console.log(errMsg);

          isShowSubBtn.value = true;
          operateTitle.value = "重新录音";
          util.showDialogue(errMsg);
          util.hideLoading();
        },
      })
    },
    fail: (errMsg) => {
      console.log(errMsg);
      util.hideLoading();
      util.showDialogue("找不到音频文件");
    }
  })
};

const handleRepairPhoneme = () => {
  if (!(currentScore.value >= scoreLimit.value || speakTimes.value <= 0)) {
    return;
  }

  const item = currentMap.value.get(currentDetail.value.oral_id);

  if (Array.isArray(item.analysis.phoneme)) {
    uni.navigateTo({
      url: `/pages/lowPricedCourse/situationalDialog/scoreResult/index?activeModal=scoreEvaluation&headerTitle=口语模仿&data=${encodeURIComponent(JSON.stringify(item))}`,
    });
    return;
  }

  util.showLoading();
  ossDownLoad(item.user_voice).then((oss: { data: any; }) => {
    fs.readFile({
      filePath: oss.data,
      success: (file) => {
        startEvaluating({
          evaluatingInfo: { sentence: item.sentences, isPhoneme: true },
          audioBuffer: file.data as ArrayBuffer,
          onSuccess: (eva) => {
            API.repairPhoneme({
              section_id: sectionId.value,
              type: item.type,
              record_id: item.record_id,
              analysis: JSON.stringify(eva),
              thirdParty: "chevon",
            }).then(res => {
              currentMap.value.set(currentDetail.value.oral_id, Object.assign(currentMap.value.get(currentDetail.value.oral_id), res));
              const tempVal = currentMap.value.get(currentDetail.value.oral_id);

              uni.navigateTo({
                url: `/pages/lowPricedCourse/situationalDialog/scoreResult/index?activeModal=scoreEvaluation&headerTitle=口语模仿&data=${encodeURIComponent(JSON.stringify(tempVal))}`,
              });
            })

            util.hideLoading();
          },
          onError: (errMsg) => {
            console.log(errMsg);
            util.showDialogue(errMsg);
            util.hideLoading();

            uni.navigateTo({
              url: `/pages/lowPricedCourse/situationalDialog/scoreResult/index?activeModal=scoreEvaluation&headerTitle=口语模仿&data=${encodeURIComponent(JSON.stringify(item))}`,
            });
          },
        })
      },
      fail: (errMsg) => {
        console.log(errMsg);
        util.hideLoading();
        util.showDialogue("找不到音频文件");
      }
    })
  })
}

const handleSetOperate = () => {
  isShowPopup.value = true;
  isShowSubBtn.value = false;
  operateTitle.value = "复述句子";

  if (currentScore.value >= scoreLimit.value || speakTimes.value <= 0) {
    if (currentIndex.value < imitationList.value.length - 1) {
      speakTimes.value = 2;
      currentIndex.value += 1;
      isShowPopup.value = false;
      progress.value += stepWidth.value;
    } else {
      if (isSynthesis.value) {
        uni.reLaunch({
          url: `/pages/lowPricedCourse/trialCourseHome/transitionPage/index?lastCourseStep=${courseStep.value}&courseStep=${courseStep.value + 1}&section_id=${sectionId.value}`,
        });
      } else {
        isOraVideo.value = true;
      }
    }
  }
};

const handleReStart = () => {
  isReStart.value = true;
  isOraVideo.value = false;
}

const handleSetPopup = () => {
  isShowPopup.value = false;
}
</script>

<style scoped lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  background-color: $uni-bg-color-minor;

  .oral-container {
    position: absolute;
    width: 37.5rem;
    top: 10rem;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    background: $uni-bg-color-minor;

    .video-container {
      position: relative;
      width: 100%;
      height: calc(100% - 3.8rem);
      overflow-x: hidden;
      overflow-y: auto;

      .header-bottom-image {
        width: 100%;
        height: 1.8rem;
        margin-top: -1rem;
      }
    }

    .oral-wrapper {
      position: relative;
      width: 100%;
      height: calc(100% - 3.8rem);
      overflow-x: hidden;
      overflow-y: auto;

      .oral-title {
        display: inline-block;
        margin-left: 2rem;
        margin-bottom: 2rem;
        font-size: 1.6rem;
        font-family: xiaolai;
        color: $uni-text-color;
      }

      .oral-image {
        width: 33.5rem;
        height: 16rem;
        margin-left: 2rem;
        margin-bottom: 2rem;
        border-radius: 1rem;
      }

      .oral-speaking {
        position: absolute;
        width: 3.3rem;
        height: 3.3rem;
        left: 2.9rem;
        top: 15.8rem;
        border-radius: 50%;
        background-color: #FDF2E0;
      }

      .oral-score-popup {
        position: absolute;
        top: 22.6rem;
        left: 50%;
        transform: translateX();
        width: 23.1rem;
        height: 12.2rem;
        background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/score-popup-bg.png");
        background-size: contain;
        background-repeat: no-repeat;
        animation-name: backgroundAppear;
        animation-duration: 0.4s;
        animation-fill-mode: both;
        animation-timing-function: cubic-bezier(0.5, 1.21, 0.88, 1.01);

        .oral-score-label {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 4.8rem;
          margin-top: 2.4rem;
          margin-bottom: 0.6rem;

          .label {
            display: inline-block;
            font-size: 1.7rem;
            font-family: xiaolai;
            color: $uni-text-color;
          }

          .score {
            display: inline-block;
            font-size: 3rem;
            font-family: baloo;
          }

          .error {
            color: $uni-text-color-error;
          }

          .success {
            color: #9BA43C;
          }
        }

        .oral-score-desc {
          position: relative;
          text-align: center;
          font-size: 1.4rem;
          font-family: xiaolai;
          color: $uni-text-color-grey;

          .desc {
            display: flex;
            align-items: center;
            justify-content: center;

            .right {
              width: 1rem;
              height: 1rem;
            }
          }
        }

        .oral-score-desc::after {
          content: "";
          position: absolute;
          top: -13px;
          right: 0;
          width: 22rem;
          height: 5rem;
        }
      }

      @keyframes backgroundAppear {
        from {
          opacity: 0;
          transform: translate(-50%, 2rem) scale(0.5);
        }

        to {
          opacity: 1;
          transform: translate(-50%, 0) scale(1);
        }
      }
    }
  }
}
</style>